package com.yasabu.wuvtdroid;

import android.app.Activity;
import android.content.Context;
import android.media.AsyncPlayer;
import android.media.AudioManager;
import android.util.Log;
import android.net.Uri;
import org.w3c.dom.*;

import javax.xml.parsers.*;
import java.net.URL;
import java.net.MalformedURLException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


public class WuvtRadio extends Activity {
    private static final String TAG = "WuvtRadio";
    enum StreamStatus {stopped, playing, stopping};
    enum RadioXMLTags {artist, title, album, label, date, time, dj};
    
    public class RadioInfo {
        String artist;
        String title;
        String album;
        String label;
        String date;
        String time;
        String dj;
        
        public RadioInfo () {
        }
        
        public void setValue(String tag, String value) {
            switch (RadioXMLTags.valueOf(tag.toLowerCase())) {
            case artist:
                artist = value;
                break;
            case title:
                title = value;
                break;
            case album:
                album = value;
                break;
            case label:
                label = value;
                break;
            case date:
                date = value;
                break;
            case time:
                time = value;
                break;
            case dj:
                dj = value;
                break;
            default:
                Log.e(TAG, "Unkown tag: ".concat(tag));
            }
        }
    }
    
    /** Called when the activity is first created. */
    public static final String WUVT_LO = "http://engine.collegemedia.vt.edu:8000/wuvt-du.ogg";
    public static final String DEBUG_STREAM_MP3 = "http://whrwfm.org:8080/lo";
    public static final String DEBUG_STREAM_OGG = "http://voxnoctem.de:9113/low.ogg";
    public static final String LATEST_TRACK_URL = "http://www.wuvt.vt.edu/playlists/latest_track_xml.php";

    private StreamStatus status;
    
    Button playButton;
    TextView artistText;
    TextView titleText;
    TextView albumText;
    TextView labelText;
    TextView airText;
    TextView djText;
    AsyncPlayer ap;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        this.status = StreamStatus.stopped;
        initControls();
    }
    
    public void onDestroy() {
    }
    
    public void initControls() {
        playButton = (Button) findViewById(R.id.PlayButton);
        artistText = (TextView) findViewById(R.id.ArtistText);
        titleText = (TextView) findViewById(R.id.TitleText);
        albumText = (TextView) findViewById(R.id.AlbumText);
        labelText = (TextView) findViewById(R.id.LabelText);
        airText = (TextView) findViewById(R.id.AirtText);
        djText = (TextView) findViewById(R.id.DjText);
        
        ap = new AsyncPlayer("wuvt-stream");
        playButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                if (status == StreamStatus.playing) {
                    status = StreamStatus.stopping;
                    playButton.setText(R.string.Stopping);
                    //Start a Thread that stops the radio stream service.
                    ap.stop();
                }
                else if (status == StreamStatus.stopped)
                {
                    status = StreamStatus.playing;
                    Uri audio_uri;
                    try {
                        audio_uri = Uri.parse(WUVT_LO);
                    }
                    catch (Exception e)
                    {
                        audio_uri = null;
                    }
                    Context c = getApplicationContext();
                    if (audio_uri != null) {
                        ap.play(c, audio_uri, false, AudioManager.STREAM_MUSIC);
                    }
                    updateInfo();
                }
            }
        });
    }
    
    public void updateInfo() {
        URL info_url;
        RadioInfo info = new RadioInfo();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            info_url = new URL(LATEST_TRACK_URL);
            Document dom = builder.parse(info_url.openStream());
            Element root = dom.getDocumentElement();
            NodeList nodes = root.getElementsByTagName("current_track");
            NodeList properties = nodes.item(0).getChildNodes();
            for (int j=0;j<properties.getLength();j++){
                Node property = properties.item(j);
                if (property.getNodeType() == Node.TEXT_NODE) {
                    continue;
                }
                String name = property.getNodeName().toLowerCase();
                String value = property.getFirstChild().getNodeValue();
                info.setValue(name, value);
            }
        } catch (MalformedURLException e) {
            Log.e(TAG, "Malformed info url");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        updateInfo(info);
    }
    
    public void updateInfo(RadioInfo info) {
        artistText.setText(info.artist);
        titleText.setText(info.title);
        albumText.setText(info.album);
        labelText.setText(info.label);
        airText.setText(info.date.concat(info.time));
        djText.setText(info.dj);
    }
    
    public void updateInfo(String artist, String title, String album, String label, String air, String dj) {
        artistText.setText(artist);
        titleText.setText(title);
        albumText.setText(album);
        labelText.setText(label);
        airText.setText(air);
        djText.setText(dj);
    }
    
    public void clearInfo() {
        updateInfo("","","","","","");
    }
}
